package com.j4dream.property.web.customer;

import com.j4dream.property.job.FileJob;
import com.j4dream.property.service.FileService;
import com.j4dream.property.service.StorageException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import static org.springframework.http.ResponseEntity.ok;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/customers")
public class CustomerController {

    @Autowired
    private FileService fileService;

    @Autowired
    private FileJob fileJob;

    @PostMapping("/upload-file")
    public ResponseEntity<?> uploadFile(MultipartFile file) {
        Resource resource = fileService.saveDataFile(file, "admin");
        try {
            return ok(new DataFileResponse(resource.getURL().toString(), resource.getFilename(), file.getSize(), resource.lastModified()));
        } catch (IOException e) {
            throw new StorageException(String.format("Fail to save file %s", resource.getFilename()), e);
        }
    }

    @GetMapping("/export-csv")
    public String exportCSV() {
        fileJob.executeJob("t");
        return "done";
    }
}
